/*
* Copyright 2011 Pavel Kozhin 
*
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed  under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License.
*
* Author: Pavel Kozhin.
*/
package org.etherframework.core.bridge
{
	import flash.errors.IllegalOperationError;
	import flash.utils.Dictionary;
	
	import org.etherframework.IEther;
	import org.etherframework.common.IDestroyable;
	import org.etherframework.core.common.IControllerFactory;
	
	[ExcludeClass]
	public final class Controllers implements IDestroyable
	{
		private var _dictionary:Dictionary = new Dictionary(true);
		private var _bridge:IBridge;
		
		public function Controllers(bridge:IBridge)
		{
			_bridge = bridge;
		}
		
		public function createController(target:Object, ether:IEther, 
										 controllerFactory:IControllerFactory):IObjectController
		{
			return controllerFactory.createController(target, ether, _bridge);
		}
		
		public function hasController(target:Object):IObjectController
		{
			return _dictionary[target] as IObjectController; 
		}
		
		public function addController(value:IObjectController):void
		{
			if (_dictionary[value.target])
				throw new IllegalOperationError("IController for target " + 
					value.target + " is already added.");
			
			_dictionary[value.target] = value;
			value.persisted();
		}
		
		public function removeController(value:IObjectController):void
		{
			if (!_dictionary[value.target])
				throw new IllegalOperationError("IController for target " + 
					value.target + " does not exist.");
			
			delete _dictionary[value.target];
		}
		
		public function walk(visitor:Function):void
		{
			for each (var item:IObjectController in _dictionary)
			{
				visitor(item);
			}
		}
		
		public function destroy():void
		{
			_dictionary = null;
			_bridge = null;
		}
	}
}